package com.soft.small.host.entity;

import com.soft.small.host.mqtt.HostMqttCallback;
import com.soft.small.app.config.APPConfig;
import com.soft.small.host.config.HostConfig;
import com.soft.small.host.service.MqttConnect;
import com.soft.small.util.mqtt.MyMqttClient;
import com.soft.util.encrypt.MD5Utils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;

@Data
@Slf4j
public class HostClient {

    private String sn;
    private String appSecret;
    private String appKey;
    private String username;
    private String password;
    private String clientId;
    private String mqttUrl;
    private String subTopic;
    private String willTopic;
    private String willMsg;
    private MyMqttClient myMqttClient;
    private String env;
    private MqttConnectOptions options;

    public HostClient(String env, String sn, String appKey, String appSecret) {
        this.env = env;
        this.sn = sn;
        this.appKey = appKey;
        this.appSecret = appSecret;
        clientId = "host-" + sn;
        Long time = System.currentTimeMillis() / 1000;
        username = appKey + "|" + sn + "|host|" + time;
        password = MD5Utils.MD5Encoding(username + appSecret, "");
        subTopic = "host/+/+/" + sn + "/+";
    }

    public void getMqttConnect(){
        log.info("主机信息是：{}",this.toString());
        if (env.toLowerCase().startsWith("chk")){
            if (env.toLowerCase().endsWith("local")){
                mqttUrl = HostConfig.Local_MqttUrl;
            }else {
                mqttUrl = HostConfig.CHK_MqttUrl;
            }
            myMqttClient = new MyMqttClient(mqttUrl, clientId, username, password);
            myMqttClient.setAppKey(APPConfig.CHK_appKey);
            myMqttClient.setAppSecret(APPConfig.CHK_appSecret);
        }else if (env.toLowerCase().startsWith("release")){
            if (env.toLowerCase().endsWith("local")){
                mqttUrl = HostConfig.Local_MqttUrl;
            }else {
                mqttUrl = HostConfig.Release_MqttUrl;
            }
            myMqttClient = new MyMqttClient(mqttUrl, clientId, username, password);
            myMqttClient.setAppKey(APPConfig.Release_appKey);
            myMqttClient.setAppSecret(APPConfig.Release_appSecret);
        }
        log.info("主机 mqttClient 信息是：{}", myMqttClient.toString());
        myMqttClient.setMqttClient(options,new HostMqttCallback(myMqttClient));
        myMqttClient.subscribe(subTopic);
    }

    public void connect(){
        //mqtt连接
        getMqttConnect();
        //登录业务
        MqttConnect mqttConnect = new MqttConnect(this);
        mqttConnect.hostOnline();
        mqttConnect.hostLineState();
    }

}
